package com.tiantianyuegou.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.tiantianyuegou.activity.BaseActivity;
import com.tiantianyuegou.R;
import com.tiantianyuegou.app.SysApplication;
import com.tiantianyuegou.cash.AccountCash;
import com.tiantianyuegou.cash.OnCashListner;
import com.tiantianyuegou.constant.Constant;
import com.tiantianyuegou.enums.PayType;
import com.tiantianyuegou.http.ApiDefine;
import com.tiantianyuegou.http.SPHelper;
import com.tiantianyuegou.model.CashInfo;
import com.tiantianyuegou.util.LoadingDialog;
import com.tiantianyuegou.util.Tools;
import com.tiantianyuegou.view.MyDialogTextView;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * 提现
 */
public class CashingActivity extends BaseActivity implements View.OnClickListener, OnCashListner, TextWatcher {

    private RelativeLayout relative_back;
    private ImageView img_title;
    private TextView text_title, text_back;
    private EditText edit_sums, edit_illustrate;
    private Button btn_confirm;
    String tmBalance, tmRedCount;
    String tbId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cashing);
      Tools.changeSystemBar(this);
        init();
        SysApplication.getInstance().addActivity(this);
    }

    @Override
    public void findViewByIds() {

    }

    @Override
    public void initListener() {

    }

    @Override
    public void initData() {

    }

    private void init() {

        text_title = (TextView) findViewById(R.id.text_title);
        img_title = (ImageView) findViewById(R.id.img_title);
        text_title.setText(R.string.cashing_title);
        img_title.setOnClickListener(this);

        relative_back = (RelativeLayout) findViewById(R.id.relative_bank);
        text_back = (TextView) findViewById(R.id.text_back);

        edit_sums = (EditText) findViewById(R.id.edit_sums);
        edit_illustrate = (EditText) findViewById(R.id.edit_illustrate);
        btn_confirm = (Button) findViewById(R.id.btn_confirm);

        tmBalance = getIntent().getStringExtra("tmBalance");
        edit_sums.setHint("最高为" + tmBalance + "元");

        edit_sums.addTextChangedListener(this);

        relative_back.setOnClickListener(this);
        btn_confirm.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_title:
                finish();
                break;
            case R.id.relative_bank:
                Intent relative_bank = new Intent();
                relative_bank.putExtra("type", "1");
                relative_bank.putExtra("tbId", tbId);
                relative_bank.setClass(CashingActivity.this, SelectBankActivity.class);
                startActivityForResult(relative_bank, 10001);
                break;

            case R.id.btn_confirm:
                Double sums = Double.valueOf(edit_sums.getText().toString());
                if (sums > Double.valueOf(tmBalance)) {
                    showMsg("提现金额大于上限");
                } else if (sums < 0.01) {
                    showMsg("提现金额下限为0.01元");
                } else {
                    CashInfo cashInfo = new CashInfo();
                    cashInfo.setCashMoney(edit_sums.getText().toString());//提现金额
                    Constant.WITHDRAW = edit_sums.getText().toString();
                    cashInfo.setDesp(edit_illustrate.getText().toString());//提现描述
                    cashInfo.setTbId(tbId);//银行卡id
                    checkPassWord(cashInfo);
                }
                break;
        }
    }

   LoadingDialog mLoadingDialog;

    //检查是否设置了余额支付密码
    private void checkPassWord(final CashInfo cashInfo) {
        mLoadingDialog = new LoadingDialog(this);
        mLoadingDialog.setMsg("正在确认订单");
        mLoadingDialog.show();
        RequestParams params = new RequestParams();
        params.addBodyParameter("tmId", SPHelper.getTmId());
        loadData(HttpRequest.HttpMethod.POST, ApiDefine.CHECK_PAY_PASS, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                mLoadingDialog.dismiss();
                Log.e("TAG", "cheek PassWord response:" + responseInfo.result);
                if (TextUtils.isEmpty(responseInfo.result)) {
                    showMsg("检查支付密码失败");
                } else {
                    try {
                        JSONObject root = new JSONObject(responseInfo.result);
                        String code = root.getString("code");
                        if ("100".equals(code)) {
                            AccountCash cash = new AccountCash(1);
//                            TODO 需换成真实数据
//                            cash.cash(CashingActivity.this, cashInfo, CashingActivity.this);
                        } else {
                            MyDialogTextView dialog = new MyDialogTextView(CashingActivity.this, "提示", "您还未设置支付密码，为保护账户安全，请先设置支付密码!");
                            dialog.setDialogCallback(new MyDialogTextView.DialogCallback() {
                                @Override
                                public void dialogOpt() {
                                    Intent intent = new Intent(CashingActivity.this, SettingBalanceActivity.class);
                                    startActivityForResult(intent, Constant.SETTING_BALANCE_REQUEST);
                                }
                            });
                            dialog.show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                mLoadingDialog.dismiss();
                Log.e("TAG", "request failure :" + s);
                showMsg("当前网络不可用，请检查您的网设置");
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10001) {
            if (resultCode == 10002) {
                String mBankname = data.getStringExtra("mBankname");
                String mBanknumber = data.getStringExtra("mBanknumber");
                text_back.setText(mBankname + "(尾号" + mBanknumber + ")");
                tbId = data.getStringExtra("tbId");
                edit_sums.setText("");
            }
        }

    }

    @Override
    public void onCashStart(PayType var1) {

    }

    @Override
    public void onCashSuccessed(PayType var1, String var2) {
        finish();
    }

    @Override
    public void onCashFailed(PayType var1, String var2) {

    }

    @Override
    public void onCashCanceled(PayType var1) {

    }

    @Override
    public void onCashConfirming(PayType var1) {

    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        String cashMoney = edit_sums.getText().toString();
        if (cashMoney != null && !"".equals(cashMoney) && !text_back.getText().toString().equals("请选择银行卡")) {
            btn_confirm.setEnabled(true);
            btn_confirm.setAlpha(1.0f);
        } else {
            btn_confirm.setEnabled(false);
            btn_confirm.setAlpha(0.5f);
        }
        if (cashMoney.contains(".")) {
            if (cashMoney.substring(cashMoney.indexOf(".")+1).length() > 2) {
                edit_sums.setText(cashMoney.substring(0,cashMoney.indexOf(".")+3));
                showMsg("提现金额只能包含两位小数");
            }
        }
    }
}
